import React, { useEffect, useState } from 'react'
import { Button, Table, Modal, notification } from 'antd';
import axios from 'axios';
import { UploadOutlined, DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
const { confirm } = Modal



export default function NewsDraft(props) {
  const [dataSource, setDataSource] = useState([])


  const { username } = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    axios.get(`http://localhost:5000/news?author=${username}&auditState=0&_expand=category`).then(res => {
      const list = res.data

      setDataSource(list)
    })
  }, [username])

  const confirmMessage = (item) => {
    confirm({
      title: 'Do you Want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: '!!!',
      onOk() {
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  // 删除函数
  const deleteMethod = (item) => {
    // // console.log(item);
    // // 后端 + 页面全部要删除

    // // 一级数据
    setDataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`http://localhost:5000/news/${item.id}`).then(res => {
      console.log('删除成功');
      console.log(res);
    })

  }
  // 点击审核
  const handleCheck = (id) => {
    axios.patch(`http://localhost:5000/news/${id}`, {
      auditState: 1
    }).then(res => {
      props.history.push('/audit-manage/list')

      notification.info({
        message: "通知",
        description: `您可以到审核列表中查看您的新闻`,
        placement: "bottomRight"
      })
    })
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.title
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button danger shape='circle' icon={<DeleteOutlined />} onClick={() => confirmMessage(item)}></Button>
          <Button type='primary' shape='circle' icon={<EditOutlined />}
            onClick={() => {
              props.history.push(`/news-manage/update/${item.id}`)
            }}
          ></Button>
          <Button type='primary' shape='circle' icon={<UploadOutlined />}
            onClick={() => handleCheck(item.id)}
          ></Button>
        </div>
      }
    },

  ];
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{ pageSize: 5 }}
        rowKey={item => item.id}
      />


    </div>
  )
}
